package zheezes.eisp.compute.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.eisp.data.orm.CalcTask;
import zheezes.eisp.data.orm.Lossy;
import zheezes.eisp.data.orm.Summator;
import zheezes.eisp.data.orm.SummatorDailyUse;


public class ZoneLossyCalcTaskHandler extends CalcTaskHandler {
	private final static Logger logger = Logger.getLogger(ZoneLossyCalcTaskHandler.class);
	
	static {
		logger.debug("ZoneLossyCalcTaskHandler Loading");
	}

	public void run() {
		Summator sm = dataAccessor.getSummatorByZone(task.getTargetId());
		if(sm != null) {
			SummatorDailyUse smdu = dataAccessor.querySummatorDailyUseByMpIdAndDate(sm.getMpId(), task.getDate());
			BigDecimal smpp = null;
			if(smdu != null && (smpp = smdu.getPp()) != null && smpp.floatValue() > 0) {
				BigDecimal sumrm = dataAccessor.sumResMeterDailyUseByZone(task.getTargetId(), task.getDate());
				if(sumrm == null) {
					sumrm = new BigDecimal(0);
				}
				BigDecimal ratio = new BigDecimal("1.0000").subtract(sumrm.divide(smpp, 4, RoundingMode.UP)).multiply(new BigDecimal("100.00"));
				
				Lossy lossy = new Lossy();
				
				lossy.setGroupId(task.getTargetId());
				lossy.setType(Lossy.DAILY_LOSSY);
				lossy.setSum(sumrm);
				lossy.setTotal(smpp);
				lossy.setRatio(ratio);
				lossy.setDate(task.getDate());
				lossy.setCalcDateTime(Calendar.getInstance().getTime());
				
				if(dataAccessor.replaceLossy(lossy) == 0) {
					task.setStatus(CalcTask.STATUS_FINISH);
					dataAccessor.replaceCalcTask(task);
				} 
			} else {
				logger.warn(String.format("no data or data is invalid, so task{id = %d} exit", task.getId()));
				return;
			}
		} else {
			logger.warn(String.format("Summator{id = %d} was not found in task{id = %d}", task.getTargetId(), task.getId()));
		}
	}
	
	public void desc() {
		SimpleDateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd");
		logger.debug(String.format("task date = %s", dfmt.format(task.getDate())));
	}
}
